#ifndef STX_PLATFORM_POSIX_TIMER_HPP
#define STX_PLATFORM_POSIX_TIMER_HPP

#include <stx/platform/posix/common.hpp>
#include <time.h>

namespace stx {

namespace posix {

template <clockid_t clock_id = CLOCK_REALTIME>
class basic_timer
{
public:
    
    basic_timer()
    {
        restart();
    }
    
    // Restart timer.
    void restart()
    {
        clock_gettime(clock_id, &t);
    }
    
    // Elapsed time in seconds.
    double elapsed()
    {
        struct timespec current_time;
        int ret = clock_gettime(clock_id, &current_time);
        if (ret != 0) {
            STX_THROW_SYSTEM_ERROR("clock_gettime() failed; clock_id: " << clock_id);
        }
        return (double) (current_time.tv_sec - t.tv_sec) + 1e-9*(current_time.tv_nsec - t.tv_nsec);
    }
    
private:
    
    struct timespec t;
};

typedef basic_timer<CLOCK_REALTIME> timer;

#ifdef CLOCK_MONOTONIC

typedef basic_timer<CLOCK_MONOTONIC> monotonic_timer;

#endif

} // namespace posix

} // namespace stx

#endif // STX_PLATFORM_POSIX_TIMER_HPP
